﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

using YouHP.Utility;
using YouHP.Model;
using YouHP.BLL;

namespace YouHP.Pages.TreatmentHistory
{
    public class PrescriptionListAjax : YouHP.Pages.BasePage
    {
        protected int DefaultPageIndex = 1;
        protected int DefaultPageSize = 5;

        protected override void ShowPage()
        {
            //base.ShowPage();
            //if (ErrorCount > 0) 
            //    return;

            int diseaseId = RequestTools.GetQueryInt("diseaseid", -1);
            if (diseaseId <= 0) 
                return;
            int pageIndex = RequestTools.GetInt("pageindex", DefaultPageIndex);
            int pageSize = RequestTools.GetInt("pagesize", DefaultPageSize);

            string prescriptionName = RequestTools.GetString("prescriptionname").Trim();
            string doctorName = RequestTools.GetString("doctorname").Trim();
            string hospitalName = RequestTools.GetString("hospitalname").Trim();

            bool prescriptionNameEnabled = (prescriptionName!= "");
            bool doctorNameEnabled = (doctorName != "");
            bool hospitalNameEnabled = (hospitalName != "");

            DiseaseInfo diseaseInfo = DiseaseBLL.Instance.GetDiseaseInfo(diseaseId);

            List<PrescriptionInfo> prescriptionList = PrescriptionBLL.Instance.GetClassicPrescriptionListByDiseaseId(diseaseId);
            if (prescriptionList == null || prescriptionList.Count == 0)
                return;

            // We need to categorize all of the prescriptions by the doctors, 
            // note that some prescripitons may be belong to any doctor.
            Dictionary<int, List<PrescriptionInfo>> doctorsAndPrescripitonsDict = new Dictionary<int,List<PrescriptionInfo>>();
            foreach (PrescriptionInfo info in prescriptionList)
            {
                int doctorId = info.DoctorId;

                //int prescriptionId = info.Id;
                if (doctorsAndPrescripitonsDict.ContainsKey(doctorId))
                {
                    doctorsAndPrescripitonsDict[doctorId].Add(info);
                }
                else
                {
                    doctorsAndPrescripitonsDict.Add(doctorId, new List<PrescriptionInfo>());
                    doctorsAndPrescripitonsDict[doctorId].Add(info);
                }
            }


            // Remove entries according to the filters.
            Dictionary<int, List<PrescriptionInfo>> filteredDoctorsAndPrescripitonsDict = new Dictionary<int, List<PrescriptionInfo>>();
            foreach (KeyValuePair<int, List<PrescriptionInfo>> pair in doctorsAndPrescripitonsDict)
            {
                int doctorId = pair.Key;
                DoctorInfo doctorInfo = DoctorBLL.Instance.GetDoctorInfo(doctorId);
                if (doctorInfo.Id <= 0)
                    continue;

                if (doctorNameEnabled && !doctorInfo.Name.Contains(doctorName))
                    continue;

                if (hospitalNameEnabled && !doctorInfo.Hospital.Contains(hospitalName))
                    continue;

                List<PrescriptionInfo> filteredPrescriptionList = new List<PrescriptionInfo>();
                foreach (PrescriptionInfo prescriptionInfo in pair.Value)
                {
                    if (prescriptionNameEnabled && !prescriptionInfo.Name.Contains(prescriptionName))
                        continue;

                    filteredPrescriptionList.Add(prescriptionInfo);
                }

                if (filteredPrescriptionList.Count == 0)
                    continue;

                filteredDoctorsAndPrescripitonsDict.Add(pair.Key, filteredPrescriptionList);
            }


            Dictionary<int, List<PrescriptionInfo>> portion = GetPortionOfDictionary(filteredDoctorsAndPrescripitonsDict, pageIndex, pageSize);

            StringBuilder sb = new StringBuilder();

            sb.Append("<div>");
            sb.Append("<table width=\"100%\">");
            sb.Append("<tr><td>");
            sb.Append("<table>");

            foreach (KeyValuePair<int, List<PrescriptionInfo>> pair in portion)
            {
                int doctorId = pair.Key;
                DoctorInfo doctorInfo = DoctorBLL.Instance.GetDoctorInfo(doctorId);
                sb.Append("<tr><td>");
                sb.Append("<div style=\"padding-left:10px; text-align:left; float:left;margin:5pt 20pt 5 10pt\">");
                sb.Append("<b><a href=\"javascript:showPrescriptionsOfDoctor(" + doctorId + ");\">");
                sb.Append("<img id=\"folder_plus" + doctorId.ToString() + "\" src=\"/support/alpha/images/folder_plus.gif\" height=\"16\" width=\"16\"/>");
                sb.Append(doctorInfo.Hospital + " " + doctorInfo.Name);
                sb.Append("</a></b>");

                // Prescription list of this doctor.
                sb.Append("<div id=\"PrescriptionListOfDoctor" + doctorId.ToString() + "\" style=\"margin:5pt 10pt 10pt 20pt; display:none\"");
                foreach (PrescriptionInfo info in pair.Value)
                {
                    sb.Append("<br>");
                    sb.Append("<img src=\"/support/alpha/images/singleprescription.gif\"/><a href=\"javascript:fetchPrescriptionData(" + info.Id + ");\">" + info.Name + "</a>");
                }
                sb.Append("</div>");

                sb.Append("</div></td></tr>");
            }

            sb.Append("</table>");
            sb.Append("</td></tr>");

            sb.Append("<tr><td height=\"10px\"></tr></td>");

            sb.Append("<tr><td align=\"center\">");
            sb.Append("</td></tr>");
            sb.Append("</table>");
            sb.Append("</div>");

            // 分页字符串
            int doctorCount = doctorsAndPrescripitonsDict.Count;
            sb.Append("<div class=\"pages\" style=\"width:200px; margin: 0px 10px 0px 10px; padding: 1px 1px 1px 1px; float:left; clear:left; border-style:dotted; border-width:1px; border-color:#a0a0a0;}\">");
            sb.Append(GetPagingString(doctorCount, pageIndex, pageSize));
            sb.Append("</div>");

            ResponseXML(sb);

        }   // ShowPage

        private string GetPagingString(int recordCount, int pageIndex, int pageSize)
        {
            StringBuilder sb = new StringBuilder();

            int pageCount = Utils.GetPageCount(recordCount, pageSize);
            for (int index = 1; index <= pageCount; index++)
            {
                if (index == pageIndex)
                    sb.AppendFormat("<a href=\"javascript:loadPagedPrescriptionList({0},{1}, '','','' )\"><b><font color=\"#0000ff\">{0}</font></b></a>\r\n", index, pageSize);
                else
                    sb.AppendFormat("<a href=\"javascript:loadPagedPrescriptionList({0},{1}, '','','' )\">{0}</a>\r\n", index, pageSize);
            }

            return sb.ToString();
        }

        private Dictionary<int, List<PrescriptionInfo>> GetPortionOfDictionary(Dictionary<int, List<PrescriptionInfo>> dict, int pageIndex, int pageSize)
        {
            Dictionary<int, List<PrescriptionInfo>> result = new Dictionary<int, List<PrescriptionInfo>>();
            int startIdx = (pageIndex-1) * pageSize;
            int endIdx = startIdx + pageSize-1;
            int index = 0;
            foreach (KeyValuePair<int, List<PrescriptionInfo>> pair in dict)
            {
                if (index < startIdx)
                {
                    index++;
                    continue;
                }
                result.Add(pair.Key, pair.Value);
                index++;

                if (index > endIdx || index >= dict.Count)
                    break;
            }

            return result;
        }

        private void ResponseXML(StringBuilder sb)
        {
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = "Text/html";
            System.Web.HttpContext.Current.Response.Expires = 0;

            System.Web.HttpContext.Current.Response.Write(sb.ToString());
            System.Web.HttpContext.Current.Response.End();
        }
    }
}
